﻿using CloudSharingStation_UWP_.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace CloudSharingStation_UWP_
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class LoginPage : Page
    {
        public LoginPage()
        {
            this.InitializeComponent();
            pgrLogin.Visibility = Visibility.Collapsed;
        }

        private async void btnLoginClick(object sender, RoutedEventArgs e)
        {
            //登陆失败就弹出对话框
            ContentDialog dialog = new ContentDialog();
            if (txtUserName.Text==null||txtPassword.Password==null)
            {
                dialog.Title = "登录失败";
                dialog.Content = "请输入用户名和密码！";
                dialog.CloseButtonText = "关闭";
                var result = dialog.ShowAsync();
                return;
            }
            // 获取用户名和密码进行登录
            string name = txtUserName.Text;
            string password = txtPassword.Password;
            // 从登录成功后开始创建单例对象
            User.SetUser(name,password); 
            pgrLogin.Visibility = Visibility.Visible;
            Task<Dictionary<HttpStatusCode, string>> task = Task<Dictionary<HttpStatusCode, string>>.Run(() => User.user.Login());
            await task;
            var resultDic = task.Result;
            pgrLogin.Visibility = Visibility.Collapsed;
            if (resultDic.First().Key != HttpStatusCode.OK)
            {
                dialog.Title = "登录失败";
                dialog.Content = "用户名或密码错误！";
                dialog.CloseButtonText = "关闭";
                var result = dialog.ShowAsync();
            }
            else
            {
                //登录成功跳转

                ResourceList currentResourceList = new ResourceList();
                User.user.token = resultDic.First().Value;
                currentResourceList.currentUser = User.user;
                Frame root = Window.Current.Content as Frame;
                root.Navigate(typeof(MainPage),currentResourceList);
            }
        }

        private void btnRegister_Click(object sender, RoutedEventArgs e)
        {
            Frame root = Window.Current.Content as Frame;
            root.Navigate(typeof(RegisterPage));
        }
    }
}
